package com.wenyl.juc.thread;

import java.util.concurrent.CountDownLatch;

/**
 * @author Swimming Dragon
 * @description: TODO
 * @date 2024年11月06日 20:12
 */
public class WaitAndNotify{
    public static void main(String[] args) {
        PrintNumWithTwoFunc printNumWithTwoFunc = new PrintNumWithTwoFunc();
        PrintA printA = new PrintA(printNumWithTwoFunc);
        PrintB printB = new PrintB(printNumWithTwoFunc);
        printA.start();
        printB.start();
        CountDownLatch countDownLatch = new CountDownLatch(5);
        countDownLatch.countDown();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}

class PrintNumWithTwoFunc{
    private int count = 1;
    private boolean flag = false;

    /**
     * 打印奇数
     */
    public void printA(){
        synchronized (this){
            while(count <= 100){
                if(!flag && count % 2 != 0){
                    System.out.println(Thread.currentThread().getName()+"打印"+ count++);
                    flag = true;
                    this.notify();
                }else{
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

    }
    /**
     * 打印偶数
     */
    public void printB(){
        synchronized (this){
            while(count <= 100){
                if(flag && count % 2 ==0){
                    System.out.println(Thread.currentThread().getName()+"打印"+ count++);
                    flag = false;
                    this.notify();
                }else{
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }


}
class PrintA extends Thread{
    private final PrintNumWithTwoFunc printNumWithTwoFunc;
    public PrintA(PrintNumWithTwoFunc printNumWithTwoFunc){
        this.printNumWithTwoFunc = printNumWithTwoFunc;
        this.setName("输出奇数");
    }
    @Override
    public void run() {
        printNumWithTwoFunc.printA();
    }

}

class PrintB  extends Thread{
    private final PrintNumWithTwoFunc printNumWithTwoFunc;
    public PrintB(PrintNumWithTwoFunc printNumWithTwoFunc){
        this.printNumWithTwoFunc = printNumWithTwoFunc;
        this.setName("输出偶数");
    }
    @Override
    public void run() {
        printNumWithTwoFunc.printB();
    }

}
